package com.lyrcsoft.springmvc.init.handler.adapter;

import com.alibaba.fastjson.JSON;
import com.lyrcsoft.springmvc.annotation.RequestParam;
import com.lyrcsoft.springmvc.annotation.ResponseBody;
import com.lyrcsoft.springmvc.servlet.RequestMappingInfo;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Map;

/**
 * @author fujc-dev@qq.com
 * @version 1.0
 */
@Component
public class AnnotationHandlerAdapter implements HandlerAdapter {
    @Override
    public boolean supports(Object handler) {
        return false;
    }

    @Override
    public Object handler(HttpServletRequest request, HttpServletResponse response, Object handler) {
        RequestMappingInfo mappingInfo = (RequestMappingInfo) handler;
        //获取HTTP请求携带参数
        Map<String, String[]> paramMap = request.getParameterMap();
        //获取方法定义的参数
        Method method = mappingInfo.getMethod();
        Parameter[] parameters = method.getParameters();
        Object[] params = new Object[method.getParameterTypes().length];
        for (int i = 0; i < parameters.length; i++) {
            Parameter parameter = parameters[i];
            RequestParam requestParam = parameter.getAnnotation(RequestParam.class);
            for (Map.Entry<String, String[]> entry : paramMap.entrySet()) {

                // 请求的参数与定义的参数一一对应
                if (requestParam != null
                        && entry.getKey() != null
                        && entry.getKey().equals(requestParam.value())) {
                    params[i] = entry.getValue()[0];
                } else if (entry.getKey() != null
                        && entry.getKey().equals(parameter.getName())) {
                    params[i] = entry.getValue()[0];
                }
            }
            // 传入request和response
            if (ServletRequest.class.isAssignableFrom(parameter.getType())) {
                params[i] = request;
            } else if (ServletResponse.class.isAssignableFrom(parameter.getType())) {
                params[i] = response;
            }
        }

        try {
            Object result = method.invoke(mappingInfo.getObj(), params);
            if (method.isAnnotationPresent(ResponseBody.class)) {
                return JSON.toJSONString(request);
            }
            return result;
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
        return null;
    }
}
